package com.ittony.blog.controller.admin;

import cn.hutool.http.HtmlUtil;
import com.github.pagehelper.PageInfo;
import com.ittony.blog.dto.ArticleParam;
import com.ittony.blog.entity.Article;
import com.ittony.blog.entity.Category;
import com.ittony.blog.entity.Tag;
import com.ittony.blog.entity.User;
import com.ittony.blog.enums.UserRole;
import com.ittony.blog.service.ArticleService;
import com.ittony.blog.service.CategoryService;
import com.ittony.blog.service.TagService;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/admin/article")
public class BackArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CategoryService categoryService;
    
    @RequestMapping(value = "")
    public String index(@RequestParam(required = false,defaultValue = "1")Integer pageIndex, @RequestParam(required = false,defaultValue = "10")Integer pageSize, @RequestParam(required = false)String status, Model model, HttpSession session) {
        HashMap<String, Object> criteria = new HashMap<>(1);
        if (status != null) {
            model.addAttribute("pageUrlPrefix","/admin/article?pageIndex");
        }else {
            criteria.put("status", status);
            model.addAttribute("pageUrlPrefix","/admin/article?status="+status+"&pageIndex");
        }
        User user = (User) session.getAttribute("user");
        if (!UserRole.ADMIN.getValue().equals(user.getUserRole())) {
            criteria.put("userId", user.getUserId());
        }
        PageInfo<Article> articlePageInfo = articleService.pageArticle(pageIndex,pageSize,criteria);
        model.addAttribute("pageInfo",articlePageInfo);
        return "Admin/Article/index";

    }

    @RequestMapping(value = "/insert")
    public String insertArticleView(Model model) {
        List<Category> categoryList = categoryService.listCategory();
        List<Tag> tagList = tagService.listTag();
        model.addAttribute("categoryList",categoryList);
        model.addAttribute("tagList",tagList);
        return "Admin/Article/insert";
    }

    @RequestMapping(value = "/insertSubmit",method = RequestMethod.POST)
    public String insertArticleSubmit(HttpSession session, ArticleParam articleParam){
        Article article = new Article();

        User user = (User) session.getAttribute("user");
        if (user != null) {
            article.setArticleUserId(user.getUserId());
        }
        article.setArticleTitle(articleParam.getArticleTitle());

        int summaryLength = 150;
        String summaryText = HtmlUtil.cleanHtmlTag(articleParam.getArticleContent());
        if (summaryText.length() > summaryLength) {
            String summary = summaryText.substring(0, summaryLength);
            article.setArticleSummary(summary);
        }else {
            article.setArticleSummary(summaryText);
        }
        article.setArticleThumbnail(articleParam.getArticleThumbnail());
        article.setArticleContent(articleParam.getArticleContent());
        article.setArticleStatus(articleParam.getArticleStatus());

        List<Category> categoryList = new ArrayList<>();
        if (articleParam.getArticleChildCategoryId()!=null) {
            categoryList.add(new Category(articleParam.getArticleParentCategoryId()));
        }
        if (articleParam.getArticleChildCategoryId()!=null) {
            categoryList.add(new Category(articleParam.getArticleChildCategoryId()));
        }
        article.setCategoryList(categoryList);

        List<Tag> tagList = new ArrayList<>();
        if (articleParam.getArticleTagIds()!=null) {
            for (int i = 0; i < articleParam.getArticleTagIds().size(); i++) {
                Tag tag = new Tag(articleParam.getArticleTagIds().get(i));
                tagList.add(tag);
            }
        }
        article.setTagList(tagList);

        articleService.insertArticle(article);
        return "redirect:/admin/article";
    }

    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    public void deleteArticle(@PathVariable("id") Integer id,HttpSession session){
        Article dbArticle = articleService.getArticleByStatusAndId(null, id);
        if (dbArticle == null) {
            return;
        }
        User user = (User) session.getAttribute("user");
        if (!Objects.equals(dbArticle.getArticleUserId(),user.getUserId()) && !Objects.equals(user.getUserRole(),UserRole.ADMIN.getValue())) {
            return;
        }
        articleService.deleteArticle(id);
    }

    @RequestMapping(value = "/edit/{id}")
    public String editArticleView(@PathVariable("id") Integer id,Model model,HttpSession session){

        Article article = articleService.getArticleByStatusAndId(null, id);
        if (article == null) {
            return "redirect:/404";
        }
        User user = (User) session.getAttribute("user");
        if (!Objects.equals(article.getArticleUserId(),user.getUserId()) && !Objects.equals(user.getUserRole(),UserRole.ADMIN.getValue())) {
            return "redirect:/403";
        }

        model.addAttribute("article",article);

        List<Category> categoryList = categoryService.listCategory();
        model.addAttribute("categoryList",categoryList);

        List<Tag> tagList = tagService.listTag();
        model.addAttribute("tagList",tagList);

        return "Admin/Article/edit";
    }

    @RequestMapping(value = "editSubmit",method = RequestMethod.POST)
    public String editArticleSubmit(HttpSession session, ArticleParam articleParam){
        Article dbArticle = articleService.getArticleByStatusAndId(null, articleParam.getArticleId());
        if (dbArticle == null) {
            return "redirect:/404";
        }
        User user = (User) session.getAttribute("user");
        if (!Objects.equals(dbArticle.getArticleUserId(),user.getUserId()) && !Objects.equals(user.getUserRole(),UserRole.ADMIN.getValue())) {
            return "redirect:/403";
        }
        Article article = new Article();
        article.setArticleThumbnail(articleParam.getArticleThumbnail());
        article.setArticleId(articleParam.getArticleId());
        article.setArticleTitle(articleParam.getArticleTitle());
        article.setArticleContent(articleParam.getArticleContent());
        article.setArticleStatus(articleParam.getArticleStatus());

        int summaryLength = 150;
        String summaryText = HtmlUtil.cleanHtmlTag(articleParam.getArticleContent());
        if (summaryText.length() > summaryLength) {
            String summary = summaryText.substring(0, summaryLength);
            article.setArticleSummary(summary);
        } else {
            article.setArticleSummary(summaryText);
        }
        List<Category> categoryList = new ArrayList<>();
        if (articleParam.getArticleChildCategoryId()!=null) {
            categoryList.add(new Category(articleParam.getArticleParentCategoryId()));
        }
        if (articleParam.getArticleChildCategoryId()!=null) {
            categoryList.add(new Category(articleParam.getArticleChildCategoryId()));
        }
        article.setCategoryList(categoryList);

        List<Tag> tagList = new ArrayList<>();
        if (articleParam.getArticleTagIds()!=null) {
            for (int i = 0; i < articleParam.getArticleTagIds().size(); i++) {
                Tag tag = new Tag(articleParam.getArticleTagIds().get(i));
                tagList.add(tag);
            }
        }
        article.setTagList(tagList);
        articleService.updateArticle(article);
        return "redirect:/admin/article";
    }

    @RequestMapping(value = "/insertDraftSubmit",method = RequestMethod.POST)
    public String insertDraftSubmit(HttpSession session, ArticleParam articleParam){
        Article article = new Article();

        User user = (User) session.getAttribute("user");
        if (user!=null){
            article.setArticleUserId(user.getUserId());
        }
        article.setArticleTitle(articleParam.getArticleTitle());

        int summaryLength=150;
        String summaryText = HtmlUtil.cleanHtmlTag(articleParam.getArticleContent());
        if (summaryText.length() > summaryLength) {
            String summary = summaryText.substring(0, summaryLength);
            article.setArticleSummary(summary);
        }else {
            article.setArticleSummary(summaryText);
        }
        article.setArticleThumbnail(articleParam.getArticleThumbnail());
        article.setArticleContent(articleParam.getArticleContent());
        article.setArticleStatus(articleParam.getArticleStatus());

        List<Category> categoryList = new ArrayList<>();
        if (articleParam.getArticleChildCategoryId()!=null) {
            categoryList.add(new Category(articleParam.getArticleParentCategoryId()));
        }
        if (articleParam.getArticleChildCategoryId()!=null) {
            categoryList.add(new Category(articleParam.getArticleChildCategoryId()));
        }
        article.setCategoryList(categoryList);

        List<Tag> tagList = new ArrayList<>();
        if (articleParam.getArticleTagIds()!=null) {
            for (int i = 0; i < articleParam.getArticleTagIds().size(); i++) {
                Tag tag = new Tag(articleParam.getArticleTagIds().get(i));
                tagList.add(tag);
            }
        }
        article.setTagList(tagList);

        articleService.insertArticle(article);
        return "redirect:/admin";
    }

}
